package com.hyt.it.ogt.kq.service.admission.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.hyt.core.base.BaseEntity;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.RemoteUtil;
import com.hyt.exception.exception.BusinessLogicException;
import com.hyt.exception.exception.BusinessRequestException;
import com.hyt.it.ogt.kq.service.admission.IAdmissionTicketInfoService;
import com.hyt.it.ogt.kq.service.admission.IExamineeInfoService;
import com.hyt.it.ogt.kq.service.admission.IExamineeTimesService;
import com.hyt.it.ogt.kq.service.gov.feign.cloudefile.CloudFileClient;
import com.hyt.it.ogt.kq.service.gov.feign.ks.model.KwExamVO;
import com.hyt.it.ogt.kq.service.gov.mapper.admission.ExamineeTimesMapper;
import com.hyt.it.ogt.kq.service.model.entity.admission.AdmissionTicketInfo;
import com.hyt.it.ogt.kq.service.model.entity.admission.ExamineeTimes;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 准考证考生批次表 服务实现类
 * </p>
 *
 * @author yanghuankun@talkweb.com.cn
 * @since 2023-02-06
 */
@Service
public class ExamineeTimesServiceImpl extends BaseServiceImpl<ExamineeTimesMapper, ExamineeTimes> implements IExamineeTimesService {

    @Resource
    IBaseLoginService loginService;
    @Resource
    CloudFileClient cloudFileClient;
    @Resource
    IAdmissionTicketInfoService iAdmissionTicketInfoService;

    @Override
    public List<ExamineeTimes> getByExamineeId(String examineeInfoId) {
        Assert.notBlank(examineeInfoId, "考生信息ID不能为空");
        return this.lambdaQuery()
                .eq(ExamineeTimes::getExamineeId, examineeInfoId)
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .list();
    }

    @Override
    public ExamineeTimes getByTimeAndAdmissinNo(String timeId, String admissionNumber) {
        Assert.notBlank(timeId, "批次ID不能为空");
        Assert.notBlank(admissionNumber, "准考证号码不能为空");
        return this.lambdaQuery()
                .eq(ExamineeTimes::getTimeId, timeId)
                .eq(ExamineeTimes::getAdmissionSerialNumber, admissionNumber)
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .last("LIMIT 1").one();
    }

    @Override
    public Integer countUnGenerateByExamineeId(String examineeInfoId) {
        return this.lambdaQuery()
                .eq(ExamineeTimes::getExamineeId, examineeInfoId)
                .eq(ExamineeTimes::getGenerateStatus, Boolean.FALSE)
                .eq(BaseEntity::getDelFlag, Boolean.FALSE)
                .count();
    }

    /**
     * 更新无考场批次信息
     *
     * @param kwExamVO
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateKwExam(KwExamVO kwExamVO, String userId) {
        String examId = kwExamVO.getId();
        AdmissionTicketInfo admissionTicketInfo = iAdmissionTicketInfoService.getByExamId(examId);
        String admissionTicketInfoId = admissionTicketInfo.getId();
        String examTime = getExamTime(kwExamVO.getBeginDate(), kwExamVO.getEndDate());
        lambdaUpdate()
                .eq(ExamineeTimes::getDelFlag, false)
                .eq(ExamineeTimes::getAdmissionTicketInfoId, admissionTicketInfoId)
                .set(ExamineeTimes::getExamStartTime, kwExamVO.getBeginDate())
                .set(ExamineeTimes::getExamEndTime, kwExamVO.getEndDate())
                .set(ExamineeTimes::getExamTime, examTime)
                .set(ExamineeTimes::getSubjectName, kwExamVO.getSubjectName())
                .set(ExamineeTimes::getUpdateBy, userId)
                .set(ExamineeTimes::getUpdateDate, LocalDateTime.now())
                .update();
    }

    @Override
    public String getExamTime(LocalDateTime start, LocalDateTime end) {
        return LocalDateTimeUtil.formatNormal(start) + " - " + LocalDateTimeUtil.formatNormal(end);
    }

    /**
     * 统计考生批次数
     *
     * @param admissionId
     * @return
     */
    @Override
    public Integer timesCount(String admissionId) {
        return lambdaQuery()
                .eq(ExamineeTimes::getAdmissionTicketInfoId, admissionId)
                .eq(ExamineeTimes::getDelFlag, false)
                .count();
    }

    /**
     * 通过准考证任务id和准考证号查询
     *
     * @param admissionId
     * @param admissionNumber
     * @return
     */
    @Override
    public List<ExamineeTimes> listByAdmissionAndNumber(String admissionId, String admissionNumber) {
        return lambdaQuery()
                .eq(ExamineeTimes::getAdmissionTicketInfoId, admissionId)
                .eq(ExamineeTimes::getAdmissionSerialNumber, admissionNumber)
                .eq(ExamineeTimes::getDelFlag, false)
                .list();
    }

    /**
     * 统计准考证任务下已经生成准考证的数量
     *
     * @param admissionId
     * @return
     */
    @Override
    public Integer timesGeneratedCount(String admissionId) {
        return lambdaQuery()
                .eq(BaseEntity::getDelFlag, false)
                .eq(ExamineeTimes::getAdmissionTicketInfoId, admissionId)
                .eq(ExamineeTimes::getGenerateStatus, true)
                .count();
    }

    @Override
    public String preview(String examineeTimeId) {
        User sysUser = loginService.getSysUser();
        if (null == sysUser) {
            BusinessLogicException.throwException(43330603, "预览准考证需要用户登录");
        }

        ExamineeTimes examineeTimes = this.getById(examineeTimeId);
        if (examineeTimes == null) {
            BusinessRequestException.throwException(43360202, "未查询到当前考生批次");
        }

        String pdfUrl = Optional.of(examineeTimes)
                .filter(ExamineeTimes::getGenerateStatus)
                .map(ExamineeTimes::getAdmissionTicketPdfUrl)
                .filter(StrUtil::isNotBlank)
                .orElseThrow(() -> BusinessLogicException.getException(43360302, "当前考生批次还未生成准考证或不存在PDF文件"));

        String waterMark = (StrUtil.isNotBlank(sysUser.getPhone()) ? sysUser.getPhone() : System.currentTimeMillis()) + IExamineeInfoService.PRE_VIEW;
        String pdfWaterMarkUrl = RemoteUtil.getOrThrows(() -> cloudFileClient.waterMark(pdfUrl, waterMark));
        return pdfWaterMarkUrl;
    }
}
